<template>
  <div>
    <el-card>
      <el-table :data="pagedata" row-key="_id" border :tree-props="{children:'children', hasChildren: 'hasChildren'}">
        <el-table-column prop="title" label="分类名称" ></el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button @click="$router.push(`edit/${scope.row._id}`)" type="text" size="small">编辑</el-button>
            <el-button @click="removeList(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- <el-table :data="categorylist">
      <el-table-column prop="_id" label="ID" width="220"></el-table-column>
      <el-table-column prop="parent.title" label="上级分类" ></el-table-column>
      <el-table-column prop="title" label="分类名称" ></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="180">
        <template slot-scope="scope">
          <el-button @click="$router.push(`edit/${scope.row._id}`)" type="text" size="small">编辑</el-button>
          <el-button @click="removeList(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table> -->
  </div>
</template>

<script>
  export default {
    data() {
      return {
        categorylist:[],
        pagedata:[]
      }
    },
    created() {
      this.feach()
        //console.log(res.data);
    },
    methods: {
      async feach(){
        let res = await this.$http.get('/rest/categories')
        this.categorylist=res.data
        this.categorylist.forEach(ele => {
          if (!ele.parent) {
            this.pagedata.push(ele)
          }
        });
        this.pagedata.forEach(e => {
          e.children=[]
          for (const ele of this.categorylist) {
            if (ele.parent) {
              if (ele.parent.title===e.title) {
                e.children.push(ele)
              }
            }
          }
        });
      },
      async removeList(row){
        this.$confirm(`是否确定要删除分类"${row.title}"`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete(`/rest/categories/${row._id}`).then(res=>{
            console.log(res.status);
            this.feach()
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        
      },
    },
  }
</script>

<style lang="scss" scoped>

</style>